﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Brain.Skinning
{
    public class BoneKeyFrameCollection
    {
        public BoneKeyFrameCollection(int bone, Frame_Skinned[] keyFrames)
        {
            this.BoneIndex = bone;
            this.KeyFrames = keyFrames;
        }
        public BoneKeyFrameCollection(SkinnedModel model, int bone, Frame_Skinned[] keyFrames)
        {
            this.BoneIndex = bone;
            this.KeyFrames = keyFrames;

            this.Bone = model.SkinnedBones[bone];
        }
        public BoneKeyFrameCollection(int bone)
        {
            this.BoneIndex = bone;
        }

        public int BoneIndex;

        public SkinnedBone Bone;

        public Frame_Skinned[] KeyFrames;

        public virtual Frame_Skinned FindKeyFrameByTime(int time)
        {
            int index;
            return FindKeyFrameByTime(time, out index);
        }
        public virtual Frame_Skinned FindKeyFrameByTime(int time, out int index)
        {
            int keyframeIndex = 0;
            int startIndex = 0;
            int endIndex = KeyFrames.Length - 1;
            Frame_Skinned frame = null;

            while (endIndex >= startIndex)
            {
                keyframeIndex = (startIndex + endIndex) / 2;

                frame = KeyFrames[keyframeIndex];

                if (frame.Time < time)
                {
                    startIndex = keyframeIndex + 1;
                }
                else if (frame.Time > time)
                {
                    endIndex = keyframeIndex - 1;
                }
                else
                {
                    break;
                }
            }

            if (frame.Time > time)
            {
                keyframeIndex--;

                if (keyframeIndex > -1)
                {
                    frame = KeyFrames[keyframeIndex];
                }
            }

            index = keyframeIndex;

            if (frame == null)
            {
                return null;
            }

            return frame;
        }
    }
}
